﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using MyClever.Lib;

namespace MyClever.DefaultPlugins
{
    public class CountWordOccurrence : MissionPlugin
    {
        [Package(Direction.Input, "Defines the data you like to analyse.")]
        enum Data2Parse { }

        [Package(Direction.Output, "Defines the extract of the counted data.")]
        enum OutputData
        {
            [Column(typeof(string), "Name of the word, which was counted.")]
            Word,
            [Column(typeof(int), "Quantity of words found in the data.")]
            NumOccurrence
        }

        [Plugin(PluginDevStatus.Development, "Counts the occurence of words in every row.")]
        public CountWordOccurrence()
        {
        }

        public override void Initialize()
        {
            //This is the first Function called by the host...
            //Put anything needed to start with here first
        }

        public override void Dispose()
        {
            //Put any cleanup code in here for when the program is stopped
        }


        protected override void Work()
        {
            List<string> words = new List<string>();

            int numRow = 0;
            DataTableReader parseDataPackage = this.GetDataReader(typeof(Data2Parse));
            while (parseDataPackage.Read())
            {
                this.AddNewLoggingMessage(typeof(Data2Parse), String.Format("parse row: {0}", numRow));

                List<KeyValuePair<string, Type>> columns = this.GetColumnNames(parseDataPackage);
                foreach (KeyValuePair<string, Type> columnOn in columns)
                {
                    // replace all white charactes (tabs, line breaks ...= with a simple white space
                    string currentColumnText = Regex.Replace(parseDataPackage[columnOn.Key].ToString().ToLower(), @"\s", " ");
                    // split all words by whitespaces
                    words.AddRange(currentColumnText.Split(' '));
                }
                numRow++;
            }

            words.Sort();

            while (words.Count > 0)
            {
                int lastIndex = words.LastIndexOf(words[0]);

                DataRow newRow = this.CreateNewRowFromPackage(typeof(OutputData));
                newRow[OutputData.Word.ToString()] = words[0];
                newRow[OutputData.NumOccurrence.ToString()] = lastIndex + 1;
                this.AddNewRowToPackage(typeof(OutputData), newRow);

                words.RemoveRange(0, lastIndex + 1);
            }
        }
    }
}
